<!-- 设计器实现-审批页 -->
<template>
  <div class="approveForm" v-loading="loading">
    <bm-form-realize
      v-if="realizeCreat"
      ref="realize"
      v-model="formData"
      :config="formConfig"
      :axios="ajax"
      :getDic="getDic"
      :downloadFn="handlerDownload"
      :headers="token"
      :otherInfo="otherInfo"
      @submit="formSubmit"
    ></bm-form-realize>
  </div>
</template>

<script>
import request from "@/plugins/axios";
import Cookies from "js-cookie";
//字典值配置
const getDicAjax = val => {
  return request({
    //这里为自己的字典值接口
    url: "/api/blade-system/dict-biz/dictionary",
    method: "get",
    params: {
      code: val
    }
  }).then(response => {
    //返回出来的数据处理，最后retuen数组
    return response.data.data;
  });
};

//下载配置
const handlerDownload = data => {
  let attachId = "";
  if (typeof data == "string") {
    attachId = data;
  } else {
    attachId = data.attachId;
  }

  request({
    url: "api/blade-resource/oss/endpoint/downloadFile",
    params: {
      attachId
    },
    method: "get",
    responseType: "arraybuffer"
  })
    .then(res => {
      if (res) {
        let headers = res.headers;
        let content = headers["content-disposition"];
        //下载后文件名
        let filename = decodeURI(content.split(";")[1].split("filename=")[1]);
        let blob = new Blob([res.data], {
          type: res.headers["content-type"]
        });
        let downloadElement = document.createElement("a");
        // 创建下载链接
        let href = URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = filename;
        document.body.appendChild(downloadElement);
        // 点击下载
        downloadElement.click();
        // 下载移除元素
        document.body.removeChild(downloadElement);
        // 释放掉blob对象
        URL.revokeObjectURL(href);
      } else {
        this.$message.error("获取下载地址失败！");
      }
    })
    .catch(() => {
      this.$message.error("下载失败！");
    });
};

export default {
  name: "approve",
  data() {
    return {
      // prop
      formData: { historyNode: [] },
      formConfig: {},
      ajax: request,
      getDic: getDicAjax,
      handlerDownload: handlerDownload,
      otherInfo: { query: {}, process: {}, taskData: {} },
      //insideData
      loading: true,
      query: {}, //传值参数
      realizeCreat: false
    };
  },
  computed: {
    token() {
      return {
        "Blade-Auth": "bearer " + Cookies.get("saber-access-token")
      };
    }
  },
  created() {
    //传参
    this.query = this.$route.query;
    if (this.query) {
      this.handlerInit();
    } else {
      this.loading = false;
      this.$message.warning("请先传递参数");
    }
  },
  methods: {
    handlerFindItem(prop, array) {
      let tag = {};
      //寻找目标组件
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element.prop == prop) {
          tag = element;
          return tag;
        } else if (element.column) {
          tag = this.handlerFindItem(prop, element.column);
          if (tag.prop) return tag;
        }
      }
      return tag;
    },
    handlerInit() {
      if (this.query.taskId) {
        Promise.all([
          this.handlerGetConfig(),
          this.handlerGetBizData(),
          this.handlerhistoryNode()
        ])
          .then(data => {
            /** 表单配置处理 **/
            let res = data[0].data;
            if (res.success) {
              Object.assign(this.formConfig, JSON.parse(res.data.formData));
              this.otherInfo = {
                query: this.query,
                process: res.data.data
              };
            } else {
              this.loading = false;
              this.$message.error(res.msg || "获取表单配置失败！");
              throw new Error();
            }

            return data;
          })
          .then(data => {
            /** 表单数据处理 **/
            let res = data[1];

            this.otherInfo.taskData = res.data;
            //finished 禁用页面
            if (this.otherInfo.taskData.taskRealFinished == true) {
              this.$set(this.formConfig, "disabled", true);
              let tag = this.handlerFindItem(
                "attachments",
                this.formConfig.column
              );
              tag.disabled = true;
            }

            let info = JSON.parse(res.data.modelJson).bizData;
            //审批按钮编辑
            if (res.data.userChoices) {
              let checkResult = this.handlerFindItem(
                  "checkResult",
                  this.formConfig.column
                ),
                checkResultList = [];

              const userChoices = JSON.parse(res.data.userChoices);
              for (let key in userChoices) {
                checkResultList.push({
                  value: key,
                  label: userChoices[key]
                });
              }

              if (checkResult.insideData) {
                this.$set(checkResult.insideData, "dataList", checkResultList);
              }
            }
            //审批历史数据清空
            if (!res.data.taskRealFinished) {
              if (info.memo) {
                delete info.memo;
              }
              if (info.checkResult) {
                delete info.checkResult;
              }
            }

            //构建
            this.realizeCreat = true;

            this.formData = info;

            return data;
          })
          .then(data => {
            /** 历史审批数据处理 **/
            let res = data[2];

            let disposeNotes = res.data;
            if (disposeNotes.length) {
              this.formData.historyNode = [];
              let arr = [];
              for (let i = 0; i < disposeNotes.length; i++) {
                if (disposeNotes[i].taskItemState == 3) {
                  arr.push(disposeNotes[i]);
                }
              }
              this.$set(this.formData, "historyNode", arr);
            }

            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
            this.$message.error("获取数据失败");
          });
      } else {
        this.loading = false;
        this.$message.warning("流程缺少taskId！");
      }
    },
    handlerGetConfig() {
      //获取表单配置
      return request({
        method: "get",
        url: "/api/rem-registrationmgrweb/otc-flow/workflowform/detail",
        params: {
          mgrOrBiz: "mgr",
          appId: this.query.appId,
          nodeId: this.query.nodeId
        }
      });
    },
    handlerGetBizData() {
      //获取表单数据
      return request.get("otc-mgr/taskform/" + this.query.taskId);
    },
    handlerhistoryNode() {
      //获取历史审批信息
      return request.get(
        "otc-mgr/taskform/" +
          this.query.bizId +
          "/taskProcess?includeRead=true&includeFuture=false&includeAutoNode=false"
      );
    },
    //表单提交
    formSubmit(data) {
      this.$confirm("您确定要提交吗？", "流程提交", {
        type: "warning"
      }).then(() => {
        this.loading = true;

        let tag = JSON.parse(JSON.stringify(data));

        if (tag.historyNode) {
          delete tag.historyNode;
        }

        let updated = JSON.parse(JSON.stringify(this.otherInfo.taskData));

        updated.checkResult = tag.checkResult;
        updated.memo = tag.memo;
        updated.formVars = {};

        let t = JSON.parse(updated.modelJson);
        t.bizData = tag;

        updated.modelJson = JSON.stringify(t);

        request
          .post(
            "api/otc-mgr/taskform/" + this.query.taskId + "/submit",
            updated
          )
          .then(res => {
            this.loading = false;
            if (res.data["0"] == "success") {
              this.$alert("提交成功！", "提示", {
                callback: () => {
                  this.$router.push("/queryPage/bjotcProcessMonitor");
                }
              });
            } else {
              this.$message.error(res.ErrorCode);
            }
          })
          .catch(() => {
            this.loading = false;
            this.$message.error("提交失败!");
          });
      });
    }
  }
};
</script>


<style lang="scss">
.approveForm {
  min-height: 70vh;
  margin: 10px 0;
  background: white;
  padding: 40px 32px 40px 32px !important;
}
</style>
